package com.mall.module.system.service.Impl;

import com.mall.common.model.UserAuth;
import com.mall.framework.security.service.MallUserDetailsService;
import com.mall.module.system.domain.entity.SysUser;
import com.mall.module.system.domain.entity.SysRole;
import com.mall.module.system.domain.entity.SysPermission;
import com.mall.module.system.mapper.SysUserMapper;
import com.mall.module.system.mapper.SysRoleMapper;
import com.mall.module.system.mapper.SysPermissionMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SysUserDetailsService implements MallUserDetailsService {

    private final SysUserMapper sysUserMapper;
    private final SysRoleMapper sysRoleMapper;
    private final SysPermissionMapper sysPermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库查询用户
        SysUser user = sysUserMapper.selectByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        
        // 检查用户状态
        if (user.getStatus() == 0) {
            throw new UsernameNotFoundException("用户已被禁用");
        }
        
        // 查询用户角色
        List<SysRole> roles = sysRoleMapper.selectRolesByUserId(user.getId());
        if (roles.isEmpty()) {
            throw new UsernameNotFoundException("用户未分配角色: " + username);
        }

        // 查询角色对应的权限
        List<Long> roleIds = roles.stream().map(SysRole::getId).collect(Collectors.toList());
        List<SysPermission> permissions = sysPermissionMapper.selectPermissionsByRoleIds(roleIds);

        // 构建权限集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        permissions.forEach(permission -> 
            authorities.add(new SimpleGrantedAuthority(permission.getPermissionKey()))
        );
        
        // 创建UserAuth对象
        UserAuth userAuth = new UserAuth();
        userAuth.setUserId(user.getId());
        userAuth.setUsername(user.getUsername());
        userAuth.setPassword(user.getPassword());
        userAuth.setAuthorities(authorities);
        
        return userAuth;
    }
} 